package org.seven.jrdp.web.app.core;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.standard.PrinterName;

import org.seven.jrdp.biz.sys.service.SysCacheService;
import org.seven.jrdp.biz.sys.service.SysDictService;
import org.seven.jrdp.biz.sys.service.SysUserService;
import org.seven.jrdp.biz.t.model.TRkd;
import org.seven.jrdp.biz.t.model.TRkdMx;
import org.seven.jrdp.biz.t.service.TCkdService;
import org.seven.jrdp.biz.t.service.TKqMxService;
import org.seven.jrdp.biz.t.service.TRkdService;
import org.seven.jrdp.commons.config.ParamConfig;
import org.seven.jrdp.commons.constant.GlobalContants;
import org.seven.jrdp.commons.exception.WebException;
import org.seven.jrdp.commons.model.Result;
import org.seven.jrdp.commons.util.DateTimeUtils;
import org.seven.jrdp.commons.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.zxing.EncodeHintType;

import net.glxn.qrgen.javase.QRCode;

@RestController
@RequestMapping("/app/core")
public class AppCoreController {
	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private TRkdService tRkdService;
	@Autowired
	private TCkdService tCkdService;
	@Autowired
	private SysCacheService sysCacheService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private TKqMxService tKqMxService;

	@RequestMapping("/test")
	public Result test() {
		return Result.SUCCESS;
	}

	@RequestMapping("/dict/{type}")
	public List<String> dict(@PathVariable String type) {
		List<String> list = sysDictService.findString(type);
		return list;
	}

	@RequestMapping("/user/{id}")
	public Result user(@PathVariable String id) {
		String name = sysUserService.getName(id);
		if (name == null) {
			throw new WebException("二维码无效");
		} else {
			return new Result().put("name", name);
		}
	}

	@RequestMapping("/kccx")
	public Result kccx(String json) {
		Map<String, Object> map = tKqMxService.getByEwm(json);
		if (map == null) {
			throw new WebException("二维码无效");
		} else {
			return new Result().put("kcxx", map);
		}
	}

	@RequestMapping("/cpck/get")
	public Result getCpck(String json) {
		Map<String, Object> map = tKqMxService.getCpck(json);
		return new Result().put("ckcp", map);
	}

	@RequestMapping("/cpck")
	public Result cpck(String json) {
		Map<String, Object> map = JsonUtils.getMap(json);
		tCkdService.cpck((String) map.get("ewm"), (String) map.get("ckry"));
		return new Result();
	}

	@RequestMapping("/rkd/find")
	public List<Map<String, Object>> findRkd() {
		return tRkdService.findRkd();
	}

	@RequestMapping("/rkd/get/{cpbh}")
	public TRkd getRkd(@PathVariable String cpbh) {
		return tRkdService.get(cpbh);
	}

	@RequestMapping("/rkd/insert")
	public Result insertRkd(String json) {
		TRkd tRkd = JsonUtils.getValue(json, TRkd.class);
		tRkdService.insert(tRkd);
		return Result.SUCCESS;
	}

	@RequestMapping("/rkd/update")
	public Result updateRkd(String json) {
		Map<String, Object> map = JsonUtils.getMap(json);
		tRkdService.xgrkd((String) map.get("cpbh1"), (String) map.get("cpbh"), DateTimeUtils.getDate((String) map.get("rkrq")), (String) map.get("xgry"));
		return Result.SUCCESS;
	}

	@RequestMapping("/rkd/delete/{cpbh}")
	public Result deleteRkd(@PathVariable String cpbh) {
		tRkdService.delete(cpbh);
		return Result.SUCCESS;
	}

	@RequestMapping("/rkdmx/find/{cpbh}")
	public List<Map<String, Object>> findRkdMx(@PathVariable String cpbh) {
		return tRkdService.findRkdMx(cpbh);
	}

	@RequestMapping("/rkdmx/get/{cpbh}/{cpxh}")
	public Map<String, Object> getRkdMx(@PathVariable String cpbh, @PathVariable String cpxh) {
		return tRkdService.getRkdMx(cpbh, cpxh);
	}

	@RequestMapping("/rkdmx/cpxh/{cpbh}")
	public Result cpxh(@PathVariable String cpbh) {
		Map<String, Object> map = new HashMap<String, Object>();
		int cpxh = tRkdService.getCountMx(cpbh);
		if (cpxh >= 98) {
			throw new WebException("已是最大序号，不允许添加入库单明细");
		}
		int xh1 = ++cpxh;
		int xh2 = ++cpxh;
		String cpxh1 = String.valueOf(xh1);
		String cpxh2 = String.valueOf(xh2);
		if (xh1 < 10) {
			cpxh1 = "0" + cpxh1;
		}
		if (xh2 < 10) {
			cpxh2 = "0" + cpxh2;
		}
		map.put("cpxh1", cpxh1);
		map.put("cpxh2", cpxh2);
		return new Result().put("cpxh", map);
	}

	@RequestMapping("/rkdmx/cpxh1/{cpbh}")
	public Result cpxh1(@PathVariable String cpbh) {
		Map<String, Object> map = new HashMap<String, Object>();
		int cpxh = tRkdService.getCountMx(cpbh);
		if (cpxh >= 98) {
			throw new WebException("已是最大序号，不允许添加入库单明细");
		}
		int xh1 = ++cpxh;
		String cpxh1 = String.valueOf(xh1);
		if (xh1 < 10) {
			cpxh1 = "0" + cpxh1;
		}
		map.put("cpxh1", cpxh1);
		return new Result().put("cpxh", map);
	}

	@RequestMapping("/rkdmx/delete/{cpbh}/{cpxh}/{user}")
	public Result deleteRkdMx(@PathVariable String cpbh, @PathVariable String cpxh, @PathVariable String user) {
		tRkdService.deleteRkdMx(cpbh, cpxh, user);
		return Result.SUCCESS;
	}

	@RequestMapping("/rkdmx/insert")
	public Result insertRkdmx(String json) {
		List<TRkdMx> list = JsonUtils.getList(json, TRkdMx.class);
		if (list.size() != 2) {
			throw new WebException("参数错误");
		}
		String kqmc = tRkdService.insertMx(list.get(0), list.get(1));
		return new Result().put("kqmc", kqmc);
	}

	@RequestMapping("/rkdmx/update")
	public Result updateRkdmx(String json) {
		TRkdMx tRkdMx = JsonUtils.getValue(json, TRkdMx.class);
		tRkdService.xgrkmx(tRkdMx.getCpbh(), tRkdMx.getCpxh(), tRkdMx.getKs());
		return Result.SUCCESS;
	}

	@RequestMapping("/rkdmx/insert1")
	public Result insertRkdmx1(String json) {
		List<TRkdMx> list = JsonUtils.getList(json, TRkdMx.class);
		if (list.size() != 1) {
			throw new WebException("参数错误");
		}
		String kqmc = tRkdService.insertMx(list.get(0));
		return new Result().put("kqmc", kqmc);
	}

	@RequestMapping("/zl/get")
	public Result getZl() {
		String zl = sysCacheService.get(GlobalContants.CACHE_KEY_ZL);
		if (zl == null || "".equals(zl)) {
			throw new WebException("未获取重量，请重新获取");
		}
		return new Result().put("zl", zl);
	}

	@RequestMapping("/zl/set/{zl}")
	public Result setZl(@PathVariable String zl) {
		sysCacheService.put(GlobalContants.CACHE_KEY_ZL, zl);
		return Result.SUCCESS;
	}

	@RequestMapping("/rkdmx/print/{cpbh}/{cpxh}")
	public Result printRkdmx(@PathVariable String cpbh, @PathVariable String cpxh) {
		HashAttributeSet hs = new HashAttributeSet();
		hs.add(new PrinterName(ParamConfig.dyj, null));
		PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
		if (pss.length == 0) {
			throw new WebException("无法找到打印机");
		}
		Map<String, Object> map = tRkdService.getRkdMx(cpbh, cpxh);
		Book book = new Book();
		PageFormat pf = new PageFormat();
		pf.setOrientation(PageFormat.PORTRAIT);
		Paper p = new Paper();
		p.setSize(PrintQRCode.W, PrintQRCode.H);
		p.setImageableArea(5, 5, PrintQRCode.W - 5, PrintQRCode.H - 5);
		pf.setPaper(p);
		book.append(new PrintQRCode(map), pf);
		PrinterJob job = PrinterJob.getPrinterJob();
		try {
			job.setPrintService(pss[0]);
			job.setPageable(book);
			job.print();
			job.print();
		} catch (Exception e) {
			e.printStackTrace();
			throw new WebException("打印失败");
		}
		return new Result("打印成功");
	}

	@RequestMapping("/rkdmx/prints/{cpbh}/{cpxh1}/{cpxh2}")
	public Result printRkdmxs(@PathVariable String cpbh, @PathVariable String cpxh1, @PathVariable String cpxh2) {
		HashAttributeSet hs = new HashAttributeSet();
		hs.add(new PrinterName(ParamConfig.dyj, null));
		PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
		if (pss.length == 0) {
			throw new WebException("无法找到打印机");
		}
		Map<String, Object> map1 = tRkdService.getRkdMx(cpbh, cpxh1);
		Map<String, Object> map2 = tRkdService.getRkdMx(cpbh, cpxh2);
		Book book1 = new Book();
		Book book2 = new Book();
		PageFormat pf = new PageFormat();
		pf.setOrientation(PageFormat.PORTRAIT);
		Paper p = new Paper();
		p.setSize(PrintQRCode.W, PrintQRCode.H);
		p.setImageableArea(5, 5, PrintQRCode.W - 5, PrintQRCode.H - 5);
		pf.setPaper(p);
		book1.append(new PrintQRCode(map1), pf);
		book2.append(new PrintQRCode(map2), pf);
		PrinterJob job1 = PrinterJob.getPrinterJob();
		PrinterJob job2 = PrinterJob.getPrinterJob();
		try {
			job1.setPrintService(pss[0]);
			job1.setPageable(book1);
			job1.print();
			job1.print();
			job2.setPrintService(pss[0]);
			job2.setPageable(book2);
			job2.print();
			job2.print();
		} catch (Exception e) {
			e.printStackTrace();
			throw new WebException("打印失败");
		}
		return new Result("打印成功");
	}
}

class PrintQRCode implements Printable {
	public static int W = 230;
	public static int H = 140;

	private Map<String, Object> map;

	public PrintQRCode(Map<String, Object> map) {
		this.map = map;
	}

	public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
		Graphics2D g2 = (Graphics2D) g;
		File file = QRCode.from((String) map.get("ewm")).withSize(600, 600).withHint(EncodeHintType.MARGIN, 0).file();
		Image image = null;
		try {
			image = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		g2.drawImage(image, 10, 20, 55, 55, null);
		g2.translate(W - 5, H - 5);
		g2.rotate(Math.toRadians(180));
		Font font = new Font("宋体", Font.BOLD, 10);
		g2.setFont(font);
		g2.setColor(Color.BLACK);
		g2.drawString((String) map.get("ggxh"), 80, 69);
		g2.drawString((String) map.get("cpbh") + "-" + (String) map.get("cpxh"), 80, 83);
		g2.drawString((String) map.get("zl"), 80, 97);
		g2.drawString((String) map.get("ks"), 80, 111);
		return 0;
	}
}